﻿//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace AstoriaOverAstoriaTests
{
    using System.Data.Services;
    using System;
    using AstoriaOverAstoria;

    public class AoATestContext<T> : AstoriaOverAstoriaContext, IDisposable
    {
        private TestService sourceService;

        private AoATestContext(MetadataMapping contextMapping, Uri serviceBaseUri)
            : base(typeof(T).FullName, contextMapping, serviceBaseUri)
        {
        }

        public static AoATestContext<T> CreateContext(MetadataMapping contextMapping)
        {
            TestService sourceService = new TestService(typeof(TestDataService<T>));

            AoATestContext<T> result = new AoATestContext<T>(contextMapping, sourceService.ServiceUri);
            result.sourceService = sourceService;
            return result;
        }

        public void Dispose()
        {
            if (this.sourceService != null)
            {
                this.sourceService.Dispose();
            }
        }
    }

    public interface IAoATestService
    {
        Type UnderlyingServiceType { get; }
        string PrepareRequestUri(string uri);
    }

    public static class AoATestService
    {
        public static Action<DataServiceConfiguration> InitializeService;
        public static bool ForceVerboseErrors = true;

        internal static void InnerInitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
            config.DataServiceBehavior.AcceptCountRequests = true;
            config.DataServiceBehavior.AcceptProjectionRequests = true;
            config.DataServiceBehavior.MaxProtocolVersion = System.Data.Services.Common.DataServiceProtocolVersion.V2;

            config.UseVerboseErrors = ForceVerboseErrors;

            if (InitializeService != null)
            {
                InitializeService(config);
            }
        }
    }

    public abstract class AoATestService<T> : DataService<T>, IAoATestService
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            AoATestService.InnerInitializeService(config);
        }

        public abstract Type UnderlyingServiceType { get; }
        public abstract string PrepareRequestUri(string uri);
    }
}